import getpath
import os
import logging
import csv
import myglobal
import config_json
from delegates import EditDelegateQt,DateTimeEditDelegateQt,DoubleViewDelegate,FloatEditDelegateQt
import sample
from PyQt5 import QtWidgets,QtCore
from DlgYanghua import DlgYanghua
import openpyxl
import re
import logging
class MyDB_Base():
    def __init__(self,mainw):
        self.inited=self.init_db()
        self.depart=None
        self.ejff=None
        self.origin_column_w=10
        self.SampleCls=sample.Sample
        self.doublefmt="%.6f"
        self.mainw=mainw
        self.m_doubleDeleget = "double"
        self.dateDelegate="date"
        self.editDelegate="edit"
        self.floatEdit="floatEdit"
        self.properties = [
            {"ele":None,"delegate":self.editDelegate,'width':130,'attr': "sampleid",'visible':True,  'header': "样品中心编号"},
            {"ele":None,"delegate":self.floatEdit,'width':80,'attr': "mass",'visible':True,  'header': "试料质量"},
            {"ele":None,"delegate":self.editDelegate,'width':80,'attr': "beizhu",'visible':True,  'header': "备注"},
        ]
    def getejff(self):
        return ""
    def getdepart(self):
        return []
        return []
    def calc(self):
        pass
    def init_db(self):
        return True
    def contextMenuEvent(self,event):
        menu = QtWidgets.QMenu(self.mainw)
        allAction = menu.addAction("全部")
        noneAction = menu.addAction("全部不选")
        validAction = menu.addAction("去除无效")
        firstAction= menu.addAction("第一个")
        # multiAction = menu.addAction("*0.4")
        # multiAction2 = menu.addAction("*0.8")
        # multiAction3 = menu.addAction("*2")
        # multiAction4 = menu.addAction("*0.5")
        # copyAction = menu.addAction("复制备注")
        # copyAction2 = menu.addAction("复制体积")
        action = menu.exec_(self.mainw.mapToGlobal(event.pos()))
        if action == noneAction:
            self.mainw.noneChannel()
        elif action == allAction:
            self.mainw.allChannel()
        elif action == validAction:
            self.mainw.validChannel()
        elif action == firstAction:
            self.mainw.firstChannel()
    def showColumnMenu(self, pos):
        pass
    def yanghua(self, pos):
        pass
    def changeYanghua(self, i, ele,yanghua, xishu):
        pass
    def import_text_bytitle(self, txt):
        pass
    def getDataDays(self, v):
        filename=config_json.setting['database']
        data=getdata(filename)
        return self.toObjects(data) 
    def resetProperties(self,items):
        pass
    def toObjects(self,samples):        
        objs=[]
        num=0
        for one in samples:
            s=self.SampleCls()
            s.num=num
            s.sampleid=one["sampleid"]
            logging.info(s.sampleid)
            s.mass=one["mass"]
            s.volume=one["volume"]
            s.items={}
            for i in range(len(one["items"])): #one in one["items"]:
                s.items[one["items"][i]]=one["conc"][i]
            objs.append(s)
            num+=1
        if len(objs)>0:
            self.resetProperties(objs[0].items)
        return objs  
    def checkBoth(self):
        name = []
        for f in self.properties:
            if f["visible"]:
                logging.info(name)
                if (f["ele"]!=None):
                    if(f["ele"][0] in name):
                        QMessageBox.information(self, "", "不能同时选择一个元素的两个通道")
                        return True
                    else:
                        name.append(f["ele"][0])
        return False
    def remove_pingxing(self,a):
        for i in range(len(a)):
            if a[i]=="_":
                return a[:i]        
        return a        
    def checkSingle(self):
        n = len(self.mainw.objects2)
        r={}
        for row_idx in range(n):
            record = self.mainw.objects2[row_idx]
            name=str(record.sampleid)
            if config_json.setting["pingxing"]==1:
                name=self.remove_pingxing(name)
            if re.match(self.mainw.sample_name_pattern,name.strip())!=None:# name.strip()[0:0+2]=="23":
                if r.get(name)!=None:
                    r[name]+=1
                else:
                    r[name]=1
        logging.info(r)
        all=[]
        for k in r.keys():
            if r[k]==1:
                all.append(k)
        if len(all)==0:
            return ""
        else:
            return ",".join(all)        
    def lims(self):
        if self.checkBoth():
            return
        ffbh = self.mainw.ui.cmb_ffbh.text()
        syy = self.mainw.ui.cmb_syy.text()
        ysry = self.mainw.ui.cmb_ysry.text()
        syyqm = self.mainw.ui.cmb_syyqm.text()
        yqbh = config_json.setting["yqbh"]
        queren = ""
        if config_json.setting["sblx"] in ["zwk","spec"]:
            pass
        else:
            single=self.checkSingle()
            if single!="":
                queren = queren+"样品(%s)没有平行样!!!\n" % single 
                queren = queren+"\n"
        queren = queren+"方法编号(%s)\n" % ffbh
        queren = queren+"实验员(%s)\n" % syy
        queren = queren+"一审(%s)\n" % ysry
        queren = queren+"实验员签名(%s)\n" % syyqm
        queren = queren+"仪器编号(%s)\n" % yqbh
        logging.info(["ejff",config_json.setting["ejff"]])
        ejff= self.mainw.ui.cmb_ff2.text()
        ejfxjs= self.mainw.ui.cmb_js2.text()
        if config_json.setting["ejff"]==1 and ejff!="" and ejfxjs!="":
            queren = queren+"二级方法(%s)\n" % ejff
            queren = queren+"二级分析技术(%s)" % ejfxjs
        r = QtWidgets.QMessageBox.question(
            self.mainw, '输出', queren, QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No, QtWidgets.QMessageBox.Yes)
        if r == QtWidgets.QMessageBox.No:
            return            
        if len(yqbh)>4:
            yqbh=yqbh[-4:]
        if self.mainw.ui.lineEdit_filename.text() == "":
            file_name = yqbh + "_" + myglobal.timestr()
        else:
            file_name = yqbh+"_"+self.mainw.ui.lineEdit_filename.text()
        path = config_json.setting["output_folder"]
        filepath = os.path.join(path, file_name)
        self.output_xlsx(filepath)
    def output_append_common(self,ws):        
        ffbh = self.mainw.ui.cmb_ffbh.text()
        syy = self.mainw.ui.cmb_syy.text()
        ysry = self.mainw.ui.cmb_ysry.text()
        yqbh = config_json.setting["yqbh"]
        syyqm = self.mainw.ui.cmb_syyqm.text()
        row = ["ffbh&" + ffbh, "", "", "", ""]
        ws.append(row)
        row = ["syy&" + syy, "", "", "", ""]
        ws.append(row)
        row = ["ysry&" + ysry, "", "", "", ""]
        ws.append(row)
        row = ["yqbh&" + yqbh, "", "", "", ""]
        ws.append(row)
        row = ["syyqm&" + syyqm, "", "", "", ""]
        ws.append(row)
        ff2= self.mainw.ui.cmb_ff2.text()
        js2= self.mainw.ui.cmb_js2.text()
        if config_json.setting["ejff"]==1 and ff2 != "" and js2 != "":
            ws.append(["ejff&" + ff2,"", "", "", ""])  # todo
            ws.append(
                ["ejfxjs&" + js2, "", "", "", ""])
        ws.column_dimensions['A'].width = 20.0        
    def output_xlsx(self, filepath):
        pass
if __name__=="__main__":
    file = os.path.join(getpath.getpath(), "930.csv")
    config_json.read_setting()
    config_json.setting['database'] = file
    db = MyDb(None)
    objs=db.getDataDays(200)
    for obj in objs:
        print(obj.sampleid)
        for one in obj.items.keys():
            print(one[0]+"_"+one[1],getattr(obj,one[0]+"_"+one[1]))       